define(["jquery","bbcare",
        "scprit/followup/app/question/question.ui.js",
        "scprit/followup/app/question/imgCollection.servers.js",
        "scprit/followup/app/question/question.servers.js"
    ],function($,$bb,$questionUi,$imgCollectionServers,$questionServers){
	var drawCanvas = {};

	// 绘制图片 初始化
	drawCanvas.init = function(imgSrc,infoParams){
        var rotateInit = infoParams.rotationAngle*1;//图片初始旋转角度
        // 基础配置
        var config = {
            width : 677,        // 设置canvas的宽
            height : 318,        // 设置canvas的高
            imgSrc : imgSrc,    // 图片路径
            maxScale : 4.0,        // 最大放大倍数
            minScale : 0.1,        // 最小放大倍数
            step : 0.1            // 每次放大、缩小 倍数的变化值
        };
        var imgStatus = {'scale' : 1.0, 'rotate' : rotateInit,"imgRotate":0};
        var lastStatus = {};
        var canvas = document.getElementById("canvas");
        canvas.width = config.width;
        canvas.height = config.height;
        var ctx = canvas.getContext("2d");
        var img = new Image();
        img.src = config.imgSrc;
        /*
         * 获取图片的标记历史记录：
         */
        var getMarkContentHistory = function(params){
            var inParams = {
                "imgId":params.imgId,
                "markIdList":JSON.parse($(params.dom).parents(".picture").attr("markIdList")),
                "userId":params.userId,
                "markType":'',
                "markTypeFlag":''
            };
            $imgCollectionServers.imgMarkHistory(inParams,getMarkContentHistoryCallback,params)
        };

        var getMarkContentHistoryCallback = function(data,params){
            if(data.success){
                var rows = data.data.rows;
                var markHtml = '';
                for(var i = 0;i < rows.length ; i++){
                    var className;
                    var inParams = {};
                    inParams.imgId = rows[i].imgId;
                    inParams.userId = rows[i].userId;
                    inParams.markId = rows[i].id;
                    inParams.markName = rows[i].markName;
                    inParams.diseaseIdList = [];
                    inParams.diseaseIdList.push(rows[i].diseaseId);
                    inParams.markType = rows[i].markType;
                    inParams.templId = rows[i].markTemplId;
                    inParams.templVersion = rows[i].markTemplVersion;
                    inParams.num = "";
                    if(rows[i].markType != "0"){
                        inParams.num = rows[i].markName.substring(2);//标记名格式：  ”标记“+ ”数字“
                        className = inParams.markType == "1" ? "mark-box-rectangle" : inParams.markType == "2" ? "mark-box-oval":inParams.markType == "3" ? "mark-box-angle mark-box-"+inParams.num :"";
                        markHtml += '<div id="" class="mark-box '+ className +'" style="border: 1px solid '+rows[i].markColour+'; top: '+rows[i].axisY+'px; left: '+rows[i].axisX+'px; width: '+rows[i].markWidth+'px; height: '+rows[i].markHeight+'px;">  '+
                            '<span class="mark-num" style="color:#333;background:'+rows[i].markColour+'" num="'+inParams.num+'">'+inParams.num+'</span>'+
                            '</div>'
                    }
                    imgStatus.rotate =  rows[i].rotationAngle;
                    imgStatus.imgRotate = rows[i].rotationAngle;
                    getHistoryMarkAnswer(inParams);
                }
                $(".canvas-box").append(markHtml);
            }
        };

        img.onload = function() {
            //获取历史记录：
            if(infoParams.markIdList){
                getMarkContentHistory(infoParams);
            }
            lastStatus = {
                'mouseX' : 0,
                'mouseY' : 0,
                'translateX' : canvas.width / 2,
                'translateY' : canvas.height /2,
                'scale' : 1.0,  // 缩放默认值
                'rotate' : 0,   // 旋转默认值
                'clipX' : -1 * img.width / 2,  // 裁剪默认开始位置x坐标
                'clipY' : -1 * img.height / 2, // 裁剪默认开始位置y坐标
                'clipWidth' :img.width,        // 裁剪默认宽
                'clipHeight' :img.height      // 裁剪默认高
            };
            //drawImgByStatus(canvas.width / 2, canvas.height / 2);
            drawImgByStatusInit(canvas.width / 2, canvas.height / 2)
        };
        //获取标记模板的类型：
        getImgMarkTemplate(infoParams);

        // 标注
        $(".con").off("click","span");
        $(".con").on("click","span",function(){
            $(this).addClass("active").siblings().removeClass("active");
            var shape = $(this).attr("shape");
            var params = {};
            params.templId = $(this).attr("templId");
            params.templVersion = $(this).attr("templVersion");
            params.markType = $(this).attr("markType");
            var num = $(".canvas-box .mark-box").length + 1;//获取标记序号
            num = markIsExist(num);
            params.markName = "标记"+ num;
            params.num = num;
            var $li = $(".mark-describe-tit ul").find('li[num="'+ num +'"]');
            var $mark = $(".canvas-box").find('.mark-num[num="'+ num +'"]').parent('.mark-box');
            if($mark.length == 0){
                if($li.length > 0 ){
                    $li.remove();
                    var formId = $li.attr("formId");
                    $(".mark-describe-con").find('form[id="'+ formId +'"]').remove();
                }
            }
            var liLength = $(".mark-describe-tit ul li").length;
            if(liLength <= num){
                getMarkContent_global(params);
            }
            mark(canvas,shape);
        });

        // 删除标记
        $("#delMark").unbind("click");
        $("#delMark").click(function(){
            var deleteMarkConfirm = function(){
                deleteMark(infoParams);
            }
            $bb.toastConfirmShow(deleteMarkConfirm,'',"您确定要删除该标记么？");
        });
        //清空标记：
        $("#emptyMark").unbind("click");
        $("#emptyMark").click(function(){
            var deleteAllMarkConfirm = function(){
                deleteAllMark(infoParams);
            };
            $bb.toastConfirmShow(deleteAllMarkConfirm,'',"您确定要清空全部标记么");
        });
            
        $("#bigBtn").click(function() {
            imgStatus.scale = (imgStatus.scale*1 >= config.maxScale*1) ? config.maxScale : imgStatus.scale + config.step;
            imageZoom(canvas.width / 2, canvas.height / 2);
        });

        $("#smallBtn").click(function() {
            imgStatus.scale = (imgStatus.scale*1 <= config.minScale*1) ? config.minScale : imgStatus.scale - config.step;
            imageZoom(canvas.width / 2, canvas.height / 2);
        });

        $("#leftRotate").click(function() {
            var rotate = parseInt(imgStatus.rotate / 90) * 90 - 90;
            imgStatus.rotate = rotate;
            imageZoom(canvas.width / 2, canvas.height / 2);
        });

        $("#rightRotate").click(function() {
            var rotate = parseInt(imgStatus.rotate / 90) * 90 + 90;
            imgStatus.rotate = rotate;
            imageZoom(canvas.width / 2, canvas.height / 2);
        });

        $("#cutBtn").click(function() {
        	if( $(".canvas-box #mainDiv").length == 0 ){
                var isResize = false;   // 裁剪box的大小可否改变
                var contact = "";       // 表示被按下的触点
                var cutDiv =    '<div id="mainDiv" class="cut-box">'+
                                '   <span id="upSpan"></span>'+
                                '   <span id="rightSpan"></span>'+
                                '   <span id="downSpan"></span>'+
                                '   <span id="leftSpan"></span>'+
                                '   <span id="leftUpSpan"></span>'+
                                '   <span id="rightUpSpan"></span>'+
                                '   <span id="rightDownSpan"></span>'+
                                '   <span id="leftDownSpan"></span>'+
                                '   <div id="cancelDiv">取消</div>'+
                                '   <div id="finishDiv">完成</div>'+
                                '</div>';
                $(".canvas-box").append(cutDiv);
                var mainDiv = document.getElementById("mainDiv");
                $(mainDiv).css({
                    "width":img.width,
                    "height":img.height,
                    "top":canvas.height / 2 - img.height / 2,
                    "left":canvas.width / 2 - img.width / 2
                });

                // 取消
                $("#cancelDiv").click(function(){
                    $(this).parent("#mainDiv").remove();
                });

                // 完成
                $("#finishDiv").click(function(){
                    var top = mainDiv.offsetTop;
                    var left = mainDiv.offsetLeft;
                    var width = mainDiv.offsetWidth;
                    var height = mainDiv.offsetHeight;   
                   // console.log(top,left,width,height);
                    /*var cutRatio_w = left - (canvas.width / 2 - img.width / 2);
                    var cutRatio_h = left - (canvas.height / 2 - img.height / 2);
                    cutRatio_w = cutRatio_w < 0 ? 0 :cutRatio_w;
                    cutRatio_h = cutRatio_h < 0 ? 0 :cutRatio_h;*/

                    lastStatus.clipX = left - canvas.width / 2,
                    lastStatus.clipY = top - canvas.height / 2,
                    lastStatus.clipWidth = width,
                    lastStatus.clipHeight = height,

                   /* lastStatus.clipX = img.width * cutRatio_w,
                    lastStatus.clipY = img.width * cutRatio_h,
                    lastStatus.clipWidth = img.width - (1-cutRatio_w),
                    lastStatus.clipHeight = img.height - (1-cutRatio_h),*/

                    drawImgByStatus(canvas.width / 2, canvas.height / 2);
                    $(this).parent("#mainDiv").remove();

                    imgCutOut_toSave(infoParams);
                    /*var data = canvas.toDataURL();
                    console.log(data);*/
                    /*data = data.split(',')[1];
                    data = window.atob(data);
                    var ia = new Uint8Array(data.length);
                    for (var i = 0; i < data.length; i++) {
                        ia[i] = data.charCodeAt(i);
                    }
                    var blob = new Blob([ia],{type:"image/png",endings:'transparent'});
                    var fd = new FormData();
                    console.log(blob);
                    fd.append('avatarFile',blob,'image.png');
                    var httprequest = new XMLHttpRequest();
                    httprequest.open('POST','/guest/avatar',true);
                    httprequest.send(fd);
                    httprequest.onreadystatechange= function () {
                        if(httprequest.status == 200 && httprequest.readyState == 4){
                            console.log(httprequest.responseText);
                            $('#returnImg').attr('src','/images/'+JSON.parse(httprequest.responseText).json);
                        }
                    };*/
                });

                // 按下鼠标
                $("#upSpan").mousedown(function(e){
                    e.stopPropagation();
                    isResize = true;
                    contact = "up";
                });
                $("#rightSpan").mousedown(function(e){
                    e.stopPropagation();
                    isResize = true;
                    contact = "right";
                });
                $("#downSpan").mousedown(function(e){
                    e.stopPropagation();
                    isResize = true;
                    contact = "down";
                });
                $("#leftSpan").mousedown(function(e){
                    e.stopPropagation();
                    isResize = true;
                    contact = "left";
                });
                $("#leftUpSpan").mousedown(function(e){
                    e.stopPropagation();
                    isResize = true;
                    contact = "leftUp";
                });
                $("#rightUpSpan").mousedown(function(e){
                    e.stopPropagation();
                    isResize = true;
                    contact = "rightUp";
                });
                $("#rightDownSpan").mousedown(function(e){
                    e.stopPropagation();
                    isResize = true;
                    contact = "rightDown";
                });
                $("#leftDownSpan").mousedown(function(e){
                    e.stopPropagation();
                    isResize = true;
                    contact = "leftDown";
                });

                // 松开鼠标
                $(window).mouseup(function(){
                    isResize = false;
                });

                // 移动鼠标
                $(window).mousemove(function(e){
                    if(isResize) {
                        switch(contact){
                            case "right": rightMove(e); break;
                            case "up": upMove(e); break;
                            case "left": leftMove(e); break;
                            case "down": downMove(e); break;
                            case "leftUp": leftMove(e); upMove(e); break;
                            case "rightUp": rightMove(e); upMove(e); break;
                            case "rightDown": rightMove(e); downMove(e); break;
                            case "leftDown": leftMove(e); downMove(e); break;
                        }
                    }
                });

                //右边移动
                function rightMove(e) {
                    var x = e.pageX; //鼠标x坐标
                    var addWidth = ""; //鼠标移动后选取框增加的宽度
                    var widthBefore = mainDiv.offsetWidth; //选取框变化前的宽度( 减去border )
                    addWidth = x - getPosition(mainDiv).left //鼠标移动后增加的宽度
                    if(widthBefore <= img.width){
                        mainDiv.style.width = addWidth + "px"; //选取框变化后的宽度
                    } else {
                        mainDiv.style.width = img.width + "px";
                    }
                }
                 
                //上边移动
                function upMove(e) {
                    var topBefore = mainDiv.offsetTop;
                    var y = e.pageY;//鼠标纵坐标
                    var addHeight = 0;
                    var mainY = getPosition(mainDiv).top;//选取框相对于屏幕上边的距离
                    addHeight = y - mainY; //增加的高度
                    var heightBefore = mainDiv.offsetHeight;
                    var bottom = topBefore + heightBefore;
                     
                    var heightAfter = heightBefore - addHeight;
                    var topAfter = topBefore + addHeight;
                     
                    if(topAfter < bottom && topAfter > -2){
                        mainDiv.style.height = heightAfter + "px";
                        mainDiv.style.top = topAfter + "px";
                    }
                }
                 
                //左边移动
                function leftMove(e) {
                    var leftBefore = mainDiv.offsetLeft;
                    var x = e.pageX;
                    var addWidth = 0;
                    var widthBefore = mainDiv.offsetWidth;
                    var mainDivLeft = getPosition(mainDiv).left;
                    var right = leftBefore + widthBefore;
                    addWidth = x - mainDivLeft;
                    var widthAfter = widthBefore - addWidth;
                    var leftAfter = leftBefore + addWidth;
                    // 防止左边框移到右边框以外区域
                    if(leftAfter < right && leftAfter > -2) {
                        mainDiv.style.width = widthAfter + "px";
                        mainDiv.style.left = leftAfter + "px";
                    }       
                }
                 
                //下边移动
                function downMove(e) {
                    var y = e.pageY;
                    var addHeight = 0;
                    var heightBefore = mainDiv.offsetHeight;
                    addHeight = y - getPosition(mainDiv).top;
                    if(heightBefore <= img.height) {
                        mainDiv.style.height = addHeight + "px";
                    } else {
                        mainDiv.style.height = img.height + "px";
                    } 
                }
                
            }
        });
        
        //保存：
        $(".save-imageProcessing").unbind("click");
        $(".save-imageProcessing").click(function(){
            saveImageProcessing(infoParams,imgStatus);
        });
        //取消：
        $(".btn-imageProcessing .cancel-imageProcessing").click(function(){
            $("#modalBox ." + infoParams.className).modal("hide");
        });
        // 画图
        function drawImgByStatus(x, y) {
        	var imgX = - ( lastStatus.clipWidth / 2 ) - (x - lastStatus.translateX) / lastStatus.scale;
            var imgY = - ( lastStatus.clipHeight / 2 ) - (y - lastStatus.translateY) / lastStatus.scale;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.save();
            ctx.translate(x, y);    // 将重心由(0,0)转为(x,y)
            ctx.rotate(imgStatus.rotate * Math.PI / 180);
            ctx.scale(imgStatus.scale, imgStatus.scale);
            // 裁剪
            var ratioW = img.width / canvas.width; 
            var ratioH = img.height / canvas.height; 
            var sx = ratioW * ( lastStatus.clipX + canvas.width / 2 );
            var sy = ratioH * ( lastStatus.clipY + canvas.height / 2 );
            var swidth = ratioW * lastStatus.clipWidth;
            var sheight = ratioH * lastStatus.clipHeight;

            ctx.drawImage(img,sx,sy,swidth,sheight,lastStatus.clipX,lastStatus.clipY,lastStatus.clipWidth,lastStatus.clipHeight);
    
            ctx.restore();
            ctx.save();
            drawTextByStatus(imgStatus.scale);
            ctx.restore();

            img.width = lastStatus.clipWidth;
            img.height = lastStatus.clipHeight;

            lastStatus = {
                'translateX' : x,
                'translateY' : y,
                'scale' : imgStatus.scale,
                'rotate' : imgStatus.rotate,
                'clipX' : - lastStatus.clipWidth / 2,
                'clipY' : - lastStatus.clipHeight / 2,
                'clipWidth' :lastStatus.clipWidth,
                'clipHeight' :lastStatus.clipHeight,
            };
        }

        var drawImgByStatusInit = function(x, y) {
            var rotate = imgStatus.rotate;
            var imgW_H = img.width / img.height;//获取图片的宽高比；
            var ratioW = img.width / canvas.width; 
      var ratioH = img.height / canvas.height;
        
            if(img.width < canvas.width && img.height < canvas.height){
                var swidth = img.height;
                var sheight = img.height;
            }else{
                if(ratioW < 1){
                    if(canvas.height < img.height){
                        if(imgW_H > 1){
                            var swidth = ratioW * lastStatus.clipWidth;
                            var sheight = ratioW * lastStatus.clipHeight;
                        }else{
                            var swidth = 0.8 * canvas.height * imgW_H;
                            var sheight = 0.8 * canvas.height;
                        }
                    }else{
                        var swidth = ratioW * lastStatus.clipWidth;
                        var sheight = ratioW * lastStatus.clipHeight;
                    }
                }else{
                    if(ratioH < 1){
                        var swidth = ratioH * lastStatus.clipWidth;
                        var sheight = ratioH * lastStatus.clipHeight;
                    }else{
                        var swidth = 0.8 * canvas.width;
                        var sheight = 0.8 * canvas.height;
                    }
                }
            }

            img.width = swidth;
            img.height = sheight;
            lastStatus = {
                'mouseX' : 0,
                'mouseY' : 0,
                'translateX' : canvas.width / 2,
                'translateY' : canvas.height /2,
                'scale' : 1.0,  // 缩放默认值
                'rotate' : 0,   // 旋转默认值
                'clipX' : - img.width / 2,
                'clipY' : - img.height / 2,
                'clipWidth' :img.width,
                'clipHeight' :img.height
            };
            var sx = (canvas.width-img.width)/2;
            var sy = (canvas.height-img.height)/2;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.save();
            ctx.translate(x, y);    // 将重心由(0,0)转为(x,y)
            ctx.rotate(rotate * Math.PI / 180);
            ctx.translate(-x, -y);
            ctx.drawImage(img,sx,sy,swidth,sheight);
            ctx.restore();
            ctx.save();
            drawTextByStatus(imgStatus.scale);
            ctx.restore();
        };
        /*
        * 图片缩放：
         */
        var imageZoom = function(x,y){
            var rotate = imgStatus.rotate - imgStatus.imgRotate;
            var swidth = lastStatus.clipWidth*imgStatus.scale;
            var sheight = lastStatus.clipHeight*imgStatus.scale;
            img.width = swidth;
            img.height = sheight;
            lastStatus = {
                'mouseX' : 0,
                'mouseY' : 0,
                'translateX' : canvas.width / 2,
                'translateY' : canvas.height /2,
                'scale' : imgStatus.scale,  // 缩放默认值
                'rotate' : imgStatus.rotate,   // 旋转默认值
                'clipX' : - lastStatus.clipWidth / 2,
                'clipY' : - lastStatus.clipHeight / 2,
                'clipWidth' :lastStatus.clipWidth,
                'clipHeight' :lastStatus.clipHeight,
            };
            var sx = (canvas.width-img.width)/2;
            var sy = (canvas.height-img.height)/2;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.save();
            ctx.translate(x, y);    // 将重心由(0,0)转为(x,y)
            ctx.rotate(imgStatus.rotate * Math.PI / 180);
            ctx.translate(-x, -y); 
            ctx.drawImage(img,sx,sy,swidth,sheight);
            drawTextByStatus(imgStatus.scale);
            ctx.restore();
            ctx.save();
            ctx.restore();
            //标记跟随canvas旋转；
            $(".mark-box").css("transform","rotate("+ rotate +"deg) scale("+ imgStatus.scale +")");
        }
        // 画百分比
        function drawTextByStatus(scale){
        	var percent = parseInt( scale * 100 ) + "%";
            $(".pic-info-percent").html(percent);
        }

        $("#mark-describe-tit ul").on("click","li",function(){
            $(this).addClass('active').siblings().removeClass('active');
            var formId = $(this).attr("formId");
            $("#mark-describe-con").find('form[id="'+ formId +'"]').removeClass("hide").siblings().addClass("hide");
        });
        //恢复infoParams初始存储值；
        $("."+infoParams.className).on('hide.bs.modal', function (e) {
            var initItem = ["birthday","gender","number","addmissionNumber","patientName","userId"];
            for(var item in infoParams){
                if($.inArray(item , initItem) < 0){
                    delete infoParams[item]
                }
            }
        })
	};

    // 获取元素相对于屏幕左边的距离，利用offsetLeft
    var getPosition = function(node) {
        var left = node.offsetLeft;
        var top = node.offsetTop;
        var parent = node.offsetParent;
        while(parent != null) {
            left += parent.offsetLeft;
            top += parent.offsetTop;
            parent = parent.offsetParent;
        }
        return {"left":left,"top":top};
    }

    /**
     * 标记
     */
    // 生成随机标记id
    var markIdRandom = function(){
        return "markBox_" + Math.floor(Math.random()*100000000);
    };
    // 创建mark
    var createMark = function(e,canvas,shape,markId,lineWidth,color,startX,startY){
        if( $("#" + markId).length == 0 ){
            var num = $(".canvas-box .mark-box").length + 1;
            num =  markIsExist(num);
            var html =  '<div id="'+ markId +'" class="mark-box mark-box-'+ shape +'" style="border:solid ' + lineWidth + 'px '+ color +';">'+
                        '   <span class="mark-num" style="color:#333;background:'+ color +'" num ="'+num+'">'+ num +'</span>'+
                        '</div>';
            $(".canvas-box").append(html);
        }
        var changingX = e.pageX - getPosition(canvas).left;
        var changingY = e.pageY - getPosition(canvas).top;
        var width = Math.abs(changingX - startX);
        var height = Math.abs(changingY - startY);
        var left = changingX - startX > 0 ? startX : changingX;
        var top = changingY - startY > 0 ? startY : changingY;
        $("#" + markId).css({
            "top":top+'px',
            "left":left+'px',
            "width":width+'px',
            "height":height+'px',
        });
    }
    // 点击标记按钮进行的标记
    var mark = function(canvas,shape){
        //var lineWidth = $("#markLineWidth").val();
        var lineWidth = 1;
        var color = $("#markColor").val();
        if(shape == "angle"){
            $("#canvas").unbind("down mousemove up");
            var oldPoint = null;
            var num = 0,markEnd = false;
            var orderLength,markId;
            var angle;
            $("#canvas").unbind("click");
            $("#canvas").click(function(e){
                e.stopPropagation();
                if(!markEnd){
                    num += 1;
                    var point = mousePosition(e,canvas);
                    if(oldPoint != null){
                        $(".canvas-box .mark-angle-0").remove();
                        drawLine(oldPoint.x, oldPoint.y, point.x, point.y,color,lineWidth,num,orderLength,markId);
                    }
                    oldPoint = point;
                    if(num == 1){
                        markId = markIdRandom();
                        orderLength = $(".canvas-box .mark-box").length + 1;
                        var order = '<div id="'+markId+'" class="mark-box mark-box-angle mark-box-'+orderLength+'" style="position:absolute;left:' + point.x + 'px;top:' + point.y + 'px;"><span class="mark-num" style="color:#333;background:'+ color +'">'+ orderLength +'</span></div>';
                        $(".canvas-box").append(order);
                    }
                    if(num == 3){
                        oldPoint = null;
                        num = 0;
                    }
                }
            });
            $("#canvas").unbind("mousemove");
            $("#canvas").mousemove(function(e){
                e.stopPropagation();
                if(!markEnd && num > 0){
                    var point = mousePosition(e,canvas);
                    $(".canvas-box .mark-angle-0").remove();
                    drawLine(oldPoint.x, oldPoint.y, point.x, point.y,color,lineWidth,'0','',markId);
                }
            });
        }else{
            $("#canvas").unbind("click mousemove");
            $("#canvas").css({"cursor":"crosshair"});
            var isMark = false;
            var contact, startX, startY, markId;
            $("#canvas").unbind("mousedown");
            $("#canvas").mousedown(function(e){
                e.stopPropagation();
                isMark = true;
                contact = "mark";
                startX = e.pageX - getPosition(canvas).left;
                startY = e.pageY - getPosition(canvas).top;
                markId = markIdRandom();
                color = $("#markColor").val();
                //是否需要绘制模板：
                var num = $(".canvas-box .mark-box").length + 1;//获取标记序号
                num =  markIsExist(num);
                var liLength = $(".mark-describe-tit ul").find('li[num="'+ num +'"]').length;
                var $checkedDom = $(".con").find('span.active');
                var shape = $checkedDom.attr("shape");
                var params = {};
                params.templId = $checkedDom.attr("templId");
                params.templVersion = $checkedDom.attr("templVersion");
                params.markType = $checkedDom.attr("markType");
                params.markName = "标记"+ num;
                params.num = num;
                if(liLength == 0){
                    getMarkContent_global(params);
                }
            });
            $(window).unbind("mouseup");
            $(window).mouseup(function(){ isMark = false; });
            $(window).unbind("mousemove");
            $(window).mousemove(function(e){
                if(isMark){
                    switch(contact){
                        case "mark": createMark(e,canvas,shape,markId,lineWidth,color,startX,startY); break;
                    }
                }
            });
        }
    };

    /**
     画点
     */
    var drawDot = function(x, y,color,lineWidth,num){
        var pointDiv = "<div class='mark-angle mark-angle-"+num+"' style='height:"+ lineWidth +"px;position:absolute;left:" + x + "px;top:" + y + "px;width:"+ lineWidth +"px;background:"+color+";'></div>";
        return pointDiv;
    }
    //获取鼠标位置
    var mousePosition = function(ev,canvas){
        var e = ev || window.event;
        var x = e.pageX - getPosition(canvas).left;
        var y = e.pageY - getPosition(canvas).top;
        return {x:x, y:y};
    };
    /**
     根据两点坐标画直线。
     */
    var drawLine = function(x1,y1,x2,y2,color,lineWidth,num,orderLength,markId){
        var odiv=document.getElementById(markId);
        var left = odiv.style.left.substring(0,odiv.style.left.indexOf("px")),top = odiv.style.top.substring(0,odiv.style.top.indexOf("px"));
        var slope; //斜率
        var direction;//坐标运动方向
        var tx = x2 - x1;
        var ty = y2 - y1;
        if(tx == 0 && ty == 0)return;
        var points = "";
        var axis;//坐标轴上的坐标
        if(num ==  0){}
        if(Math.abs(tx) >= Math.abs(ty)){//在x轴上移动
            direction = tx > 0 ? 1 : -1;
            tx = Math.abs(tx);
            slope = ty / tx;
            axis = x1;
            if(num == 0){ tx = tx-1}
            for(var i = 0; i < tx; i++){
                points += drawDot(axis-left, y1*1-top + i * slope,color,lineWidth,num);
                axis += direction;
            }
        }else{//在y轴上移动
            direction = ty > 0 ? 1 : -1;
            ty = Math.abs(ty);
            slope = tx / ty;
            axis = y1;
            if(num == 0){ ty = ty-1}
            for(var i = 0; i < ty; i++){
                points += drawDot(x1*1-left + i * slope, axis-top,color,lineWidth,num);
                axis += direction;
            }
        }
        $("#"+markId).append(points);
        return false
    };

    /*
    *   裁剪后保存：
     */
    var imgCutOut_toSave = function(params){
        var sessinonName = JSON.parse($bb.getSessionStorage("account")).alias;
        var inParams = {
            "fileInfo":{
                "imgId":params.imgId
            },
            "oprInfo":{
                "opCode":"1121", //1121保存裁剪后的新图片；
                "opNote":"医生【"+sessinonName+"】裁剪对"+params.imgName+"图片文件进行裁剪",
                "opType":"2" //2门诊；
            },
            "userInfo":{
                "userId":params.userId,
            }
        }

        $imgCollectionServers.imgCutOut_toSave(inParams,imgCutOut_toSaveCallback,params);
    }
    //裁剪后的回调函数：
    var imgCutOut_toSaveCallback = function(data,params){
        //console.log(data);
    };

    //查询影像标记模板：
    var getImgMarkTemplate = function(params){
        var inParams = {
            "equipId":params.equipId,
            "diseaseIdList":params.diseaseTypeId,
            "markType":'',
            "markTypeFlag":''
        };
        $imgCollectionServers.imgMarkTemplate(inParams,getImgMarkTemplateCallback,params);
    };
    var getImgMarkTemplateCallback = function(data,params){
        if(data.success){
            var rows = data.data.rows;
            var html = '';
            for(var i = 0;i < rows.length;i++){
                var style = "",icon;
                var markType = rows[i].markType;
                var shape =  markType == "1" ? "rectangle" : markType == "2" ? "oval" : markType == "3" ? "angle":"";
                var icon =  markType == "1" ? "icon-rectangle" : markType == "2" ? "icon-oval" : markType == "3" ? "icon-angle":"";
                var templVersion = rows[i].templVersion;
                var templId =  rows[i].templId;
                if(markType == "3"){
                    style = "style='display:none;'";
                }
                if(markType != "0"){
                    html += '<span shape ="'+shape+'" templVersion = "'+templVersion+'" templId = "'+templId+'" markType = "'+markType+'" '+ style +'><i class="'+ icon +'"></i>'+rows[i].templName+'</span>';
                }else{
                    if(!params.markIdList || (typeof params.markIdList == 'object' && params.markIdList.length == 0)){
                        //获取整个图片的标记模板：
                        getMarkContent_global({"templVersion":templVersion,"templId":templId,"markType":markType,"markId":''});
                    }
                }
            }
            if((rows.length == 1 && rows[0].markType == "0") || rows.length == 0){
                $(".mark-toolbar").css("display","none");
            }
            $("#img_templateBox").html(html);
        }
    }

    /*
    * 保存按钮：
     */
    var saveImageProcessing = function(params,imgStatus){
        var inParams = {};
        inParams.markList = [];
        inParams.fileInfo = {};
        inParams.oprInfo = {};
        var flag = false;
        $("#mark-describe-tit ul li").each(function(){
            if($(this).attr("markId")){
                flag = true;
                return false;
            }
        });
        $("#mark-describe-tit ul li").each(function(){
            var indexObj = {};
            var top,left,width,height,markColor,rotationAngle;
            if($(this).attr("markType") != "0" ){
                var num = $(this).attr("num");
                var $mark_box = $(".canvas-box").find('span[num="'+num+'"]').parent(".mark-box");
                top = $mark_box.css("top");
                left = $mark_box.css("left");
                top = top.substring(0,top.indexOf("px"));
                left = left.substring(0,left.indexOf("px"));
                width = $mark_box.width();
                height = $mark_box.height();
                markColor = $mark_box.css("border-color");
            }
            indexObj.axisX = left*1;
            indexObj.axisY = top*1;
            indexObj.markWidth = width;
            indexObj.markHeight = height;
            indexObj.markColour = markColor;
            indexObj.markName = $.trim($(this).html());
            indexObj.markId = $(this).attr("markId");
            indexObj.markType = $(this).attr("markType");//0,1,2,3
            indexObj.templId = $(this).attr("templId");
            indexObj.templVersion = $(this).attr("templVersion")*1;
            indexObj.rotationAngle = imgStatus.rotate;
            indexObj.values = [];
            var formId = $(this).attr("formId");
            var questiones = $questionServers.getDataForDom(formId);
            for(var item in questiones){
                indexObj.values.push({
                    "dataCode":'',
                    "dataId":item,
                    "dataName":$("#"+formId).find('[name="'+ item +'"]').parents("div.control-input").prev('label.control-label').html(),
                    "dataValue":questiones[item]
                });
            };
            inParams.markList.push(indexObj);
        });
        inParams.fileInfo = {
            "imgId":params.imgId,
            "diseaseId":params.diseaseTypeId[0],
            "userId":params.userId,
        }
        var sessinonName = JSON.parse($bb.getSessionStorage("account")).alias;
        var flagText = flag ? "修改" : "添加";
        inParams.oprInfo = {
            "opCode":"1118", //1118添加或修改文件标记；
            "opNote":"【"+sessinonName+"】医生"+ flagText +"了【"+ params.patientName +"】患者的【"+ $(".pic-info-name").html() +"】图片影像标记",
            "opType":"2" //2门诊；
        };
        getMarkContent_toSave(inParams,params);
    }
    var getMarkContent_toSave =  function(inParams,params){
        $imgCollectionServers.imgMark_modifyAndAdd(inParams,getMarkContent_toSaveCallback,params)
    }
    var getMarkContent_toSaveCallback = function(data,params){
        if(data.success){
            $bb.toastShow("保存成功",1500);
            $(params.dom).parents(".picture").attr("markIdList",JSON.stringify(data.data.markIdList));
            $("#mark-describe-tit ul li").each(function(){
                var index = $(this).index();
                $(this).attr("markId",data.data.markIdList[index]);
            });
        }else{
            $bb.toastShow(data.msg,1500);
        }
    }

    /*
    * 获取某个历史标记的问卷答案：
     */
    var getHistoryMarkAnswer = function(params){
        var inParams = {
            "imgId":params.imgId,
            "markId":params.markId,
            "userId":params.userId
        }
        $imgCollectionServers.imgMarkContentAndAnswer(inParams,getHistoryMarkAnswerCallback,params);
    }
    var getHistoryMarkAnswerCallback = function(data,params){
        if(data.success){
            params.values = data.data;
            getMarkContent_global(params);
        }
    }
    /*
    * 获取标记模板内容
     */
    //获取整个图片的模板内容：
    var getMarkContent_global = function(params){
        var inParams = {
            "templVersion":params.templVersion*1,
            "templId":params.templId
        }
        $imgCollectionServers.imgMarkTemplateContent(inParams,getMarkContent_globalCallback,params);
    }
    var getMarkContent_globalCallback = function(data,params){
        if(data.success){
            var questValues = params.values;
            $questionUi.init_mark({
                id: "mark-describe-con",
                status: "default",
                list: data.data.questiones,   // 问卷
                values: questValues,
                markTitle:params.markName ? params.markName:"全局标记",
                markType:params.markType,
                markId:params.markId,
                num:params.num ? params.num : "",
                templVersion:params.templVersion*1,
                templId:params.templId
            });
        }
    }

    /*
    * 删除影像文件标记(单个)：
    * 
     */
    var deleteMark = function(params){
        var sessinonName = JSON.parse($bb.getSessionStorage("account")).alias;
        //获取选中的标记id
        var $checkedDom = $("#mark-describe-tit ul").find('li[class*="active"]');
        var markType = $checkedDom.attr("markType");
        if(markType != "0"){
            var markId = $checkedDom.attr("markId");
            var formId = $checkedDom.attr("formId");
            var markTitle = $checkedDom.html();
            var num = $checkedDom.attr("num");
            if(markId){
                 params.markId = markId;
                 params.num = num;
                var markIdList = [];
                markIdList.push(markId);
                var inParams = {
                    "markInfo":{
                        "markIdList":markIdList,
                        "userId":params.userId,
                    },
                    "oprInfo":{
                        "opCode":"1120", //1120删除文件标记
                        "opNote":"【"+sessinonName+"】医生删除了【"+ params.patientName +"】患者的【"+ $(".pic-info-name").html() +"】图片的【"+ markTitle +"】",
                        "opType":"2" //2门诊；
                    }
                }
                $imgCollectionServers.imgMark_toDeal(inParams,deleteMarkCallback,params); 
            }else{
                $checkedDom.remove();
                $("#mark-describe-con").find('form[id="'+formId+'"]').remove();
                var firstDom = $('.mark-describe-tit ul li').eq(0).addClass('active');
                var formId = firstDom.attr("formId");
                $("#mark-describe-con").find('form[id="'+formId+'"]').removeClass("hide");
                $(".canvas-box").find('span[num="'+num+'"]').parent(".mark-box").remove();
            }
        }else{
            $bb.toastShow("图片的全局标记模板不可以删除",1500);
        }
    }
    var deleteMarkCallback = function(data,params){
        if(data.success){
            $bb.toastShow("删除成功",1500);
            var $checkedDom = $("#mark-describe-tit ul").find('li[class*="active"]');
            var formId = $checkedDom.attr("formId");
            $checkedDom.remove();
            $("#mark-describe-con").find('form[id="'+formId+'"]').remove();
            var imgId = JSON.parse($(params.dom).parents(".picture").attr("markIdList"));
            imgId.splice($.inArray(params.markId,imgId),1);
            if(imgId.length == 0){
                imgId = '';
            }else{
                imgId = JSON.stringify(imgId);
                var first = $('.mark-describe-tit ul li').eq(0).addClass('active');
                var formId = first.attr("formId");
                $("#mark-describe-con").find('form[id="'+formId+'"]').removeClass("hide");
            }
            $(params.dom).parents(".picture").attr("markIdList",imgId);
            $(".canvas-box").find('span[num="'+params.num+'"]').parent('.mark-box').remove();
            params.markIdList = imgId;
            delete params.markId;
            delete params.num;
        }else{
            $bb.toastShow("删除失败",1500);
        }
    }

    //清空影像标记：
    var deleteAllMark = function(params){
        var sessinonName = JSON.parse($bb.getSessionStorage("account")).alias;
        $("#mark-describe-tit ul li").each(function(){
            var markType = $(this).attr("markType");
            if(markType != "0"){
                var markId = $(this).attr("markId");
                var formId = $(this).attr("formId");
                var num = $(this).attr("num");
                if(markId){
                    var markIdList = [];
                    markIdList.push(markId);
                    var inParams = {
                        "markInfo":{
                            "markIdList":markIdList,
                            "userId":params.userId,
                        },
                        "oprInfo":{
                            "opCode":"1120", //1120删除文件标记
                            "opNote":"【"+sessinonName+"】医生清空了【"+ params.patientName +"】患者的【"+ $(".pic-info-name").html() +"】图片的全部标记",
                            "opType":"2" //2门诊；
                        }
                    }
                    $imgCollectionServers.imgMark_toDeal(inParams,deleteAllMarkCallback,params); 
                }else{
                    $(this).remove();
                    $("#mark-describe-con").find('form[id="'+formId+'"]').remove();
                    $(".canvas-box").find('.mark-num[num="'+num+'"]').parent('.mark-box').remove();
                    var $templ0 = $("#mark-describe-tit ul").find('li[markType="0"]');
                    $templ0.addClass("active");
                    var formId0 = $templ0.attr("formId");
                    $("#mark-describe-con").find('form[id="'+formId0+'"]').removeClass("hide");
                }
            }
        });
    }
    var deleteAllMarkCallback = function(data,params){
        if(data.success){
            $bb.toastShow("图片标记已经全部清空",1500);
            $(".canvas-box .mark-box").detach();
            var $templ0 = $("#mark-describe-tit ul").find('li[markType="0"]');
            var formId0 = $templ0.attr("formId");
            var markId = $templ0.attr("markId");
            var markIdList = JSON.stringify([markId]);
            $("#mark-describe-con").find('form[id="'+formId0+'"]').removeClass("hide");
            $(params.dom).parents(".picture").attr("markIdList",markIdList);
            $("#mark-describe-con form").each(function(){
                var id = $(this).attr("id")
                if( id != formId0){
                    $(this).remove();
                    $("#mark-describe-tit ul").find('li[formId="'+ id +'"]').remove();
                }
            });
        }else{
            $bb.toastShow("清空失败",1500);
        }
    }

    //判断标记序号是否已经存在：
    var markIsExist = function(num){
        var lens = $(".canvas-box").find('.mark-num[num="'+num+'"]').parent(".mark-box").length;
        if( lens > 0){
            do{
                num ++;
            }while($(".canvas-box").find('.mark-num[num="'+num+'"]').parent(".mark-box").length > 0)
        }
        return num;
    }
    return drawCanvas;
});